/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hu.kovacsp.scala.discovery.examples.dao

import com.weiglewilczek.slf4s.Logging
import hu.kovacsp.scala.discovery.jdbc.ManualPoolingDriver
import java.io.Serializable
import java.sql.Connection
import java.sql.DriverManager
import java.sql.ResultSet

object GenericDaoByScala {
  def main(args: Array[String]): Unit = {
    val driver = new ManualPoolingDriver("org.h2.Driver", "example")
    driver setupDriver "jdbc:h2:˜/test;user=sa;password=sa"
    val userRepo = new DBUserRepository
    userRepo.save(new User("peter", "kovacs"))
  }

}

case class User(firstName: String, lastName: String)

trait GenericDao[T] {
  def findAll():List[T]
  def save(entity:T):T
  def remove(entity:T):Unit
  def findById(id:Serializable):T
}

trait UserDao extends GenericDao[User] {
  def findAll():List[User]
  def findByLastName(name: String): List[User]
  def save(entity: User): User
  def remove(entity: User): Unit
  def findById(id:Serializable):User
  //more finders here…
}

class DBUserRepository extends UserDao with Logging{
  val conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:example")
  def save(entity: User): User = {
    val stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)
    
    val result = stmt.executeQuery("select 1");
    logger debug "has first row=" + result.first
//    val stmt = conn.createStatement
//    val result = stmt.execute("insert into User (id, firstName, lastName)" +
//                        "values ("+ entity.firstName +")")
//    
    new User("peter", "kovacs")
  }

  def findByLastName(name: String): List[User] = {null}
  def remove(entity: User): Unit = {}
  def findById(id:Serializable):User = {null}
  def findAll(): List[User] = {null}
}

//class WSUserRepository extends UserDao{
//
//}